﻿using MediatR;
using SheepCultivation.Common.Domain.Beginning;
using SheepCultivation.Common.Domain.SheepBasicInformation;
using SheepCultivation.Common.Domain.Week2;
using SheepCultivation.Common.Dto;
using SheepCultivation.Common.Infrastructure.Interface;
using SheepCultivation.Enum;
using Yitter.IdGenerator;

namespace SheepCultivation.API.AddliCation.BeginningW
{
    public class MalePeriodicCreateHandler : IRequestHandler<MalePeriodicCreateCommon, Result>
    {
        public readonly IBaseRepository<MalePeriodic> MalePeriodicRepository;
        public readonly IBaseRepository<BasicInformation> BasicInformationRepository;

        public MalePeriodicCreateHandler(IBaseRepository<MalePeriodic> malePeriodicRepository, IBaseRepository<BasicInformation> basicInformationRepository)
        {
            MalePeriodicRepository = malePeriodicRepository;
            BasicInformationRepository = basicInformationRepository;
        }

        public async Task<Result> Handle(MalePeriodicCreateCommon request, CancellationToken cancellationToken)
        {
            var res = new Result() { Code = (int)CommonEnumCode.error };
            try
            {
                var num = new DocumentnumberDto();
                var list = new MalePeriodic()
                {
                    MalePeriodicReceiptNumber = DateTime.Now.ToString("yyyyMMdd") + num.Num,
                    MalePeriodicPeriodicDate = request.MalePeriodicPeriodicDate,
                    MalePeriodicSerialNumber = YitIdHelper.NextId().ToString(),
                    BreedingSheepArchiveId = request.BreedingSheepArchiveId,
                    BuildingId = request.BuildingId,
                    ColumnsId = request.ColumnsId,
                    MalePeriodicNumber = request.MalePeriodicNumber,
                    MalePeriodicWeight = request.MalePeriodicWeight,
                    Remark = request.Remark
                };
                num.Num++;
                MalePeriodicRepository.Add(list);
                var list1 = BasicInformationRepository.GetAll().Where(x => x.BreedingSheepArchiveId == request.BreedingSheepArchiveId).ToList();
                foreach (var item in list1)
                {
                    item.BuildingId = request.BuildingId;
                    item.ColumnsId = request.ColumnsId;
                    item.SheepStatus = 1;
                    BasicInformationRepository.Update(item);
                }
                
                res.Code = (int)CommonEnumCode.success;
                res.Msg = "种公期初表新增";
            }
            catch (Exception ex)
            {

            }
            return res;
        }
    }
}
